package com.nexgo.payment.trans.balance;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.nexgo.payment.aop.annotation.TransCondition;
import com.nexgo.payment.trans.TransFlow;
import com.nexgo.data.entity.RecvData;
import com.nexgo.oaf.apiv3.emv.EmvAlgorithmTypeEnum;
import com.nexgo.oaf.apiv3.emv.EmvChannelTypeEnum;
import com.nexgo.oaf.apiv3.emv.EmvProcessResultEntity;
import com.nexgo.oaf.apiv3.emv.EmvTransDataEntity;
import com.nexgo.oaf.apiv3.emv.EmvTransFlowEnum;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.trans.AbsTransPresenter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 余额查询业务实现类
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年08月21日
 */
@TransCondition
@TransFlow(checkNeedElectronicSignature = false, checkNeedReceipt = false)
public class BalancePresenter extends AbsTransPresenter implements BalanceContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(BalancePresenter.class.getSimpleName());

    private BalanceContract.View mView;

    protected BalancePresenter(@NonNull BalanceContract.View view, @NonNull DataSource repository) {
        super(view, repository);
        mView = checkNotNull(view);
        mView.setPresenter(this);
    }

    @Override
    protected TransData getTransData() {
        TransData transData = new TransData();
        transData.setTransType(TransType.QUERY);
        return transData;
    }

    @Override
    protected EmvTransDataEntity getEmvTransData(EmvChannelTypeEnum channelType) {
        EmvTransDataEntity emvTransData = new EmvTransDataEntity();
        emvTransData.setChannelType(channelType);
        emvTransData.setB9C((byte) 0x31);
        emvTransData.setTransAmt("000000000000");
        emvTransData.setIsDefaultEC(false);
        emvTransData.setIsSupportEC(false);
        emvTransData.setTermId(mRepository.getParamValue(PreferencesConstants.TERMINAL_ID));
        emvTransData.setMerId(mRepository.getParamValue(PreferencesConstants.MERCHANT_ID));
        emvTransData.setMerName(mRepository.getParamValue(PreferencesConstants.MERCHANT_NAME));
        emvTransData.setTransDate(new SimpleDateFormat("yyMMdd", SysConstant.LOCALE).format(new Date()));
        emvTransData.setTransTime(new SimpleDateFormat("hhmmss", SysConstant.LOCALE).format(new Date()));
        emvTransData.setTraceNo(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        emvTransData.setAlgType("1".equals(mRepository.getParamValue(PreferencesConstants.EMV_SUPPORT_SM2)) ?
                EmvAlgorithmTypeEnum.SM2 : EmvAlgorithmTypeEnum.RSA);
        if (channelType == EmvChannelTypeEnum.FROM_PICC) {
            emvTransData.setProcType(EmvTransFlowEnum.QPASS);
            emvTransData.setIsForceOnline(true);
        } else {
            emvTransData.setProcType(EmvTransFlowEnum.FULL);
            emvTransData.setChannelType(EmvChannelTypeEnum.FROM_ICC);
        }
        return emvTransData;
    }

    @Override
    protected void onFirstAction() {
        postMainThread(() -> mView.showReadCard(mTransData));
    }

    @Override
    public void importActionResult(ActionResult actionResult) {
        Object data = actionResult.getData();
        ActionStep step = (ActionStep) actionResult.getAction().getActionStep();
        int ret = actionResult.getRet();
        mLog.debug("curr action step {} ret {}", step, actionResult.getRet());
        //成功处理进行处理，否则让父类处理
        if (ret == ActionResult.SUCC) {
            switch (step) {
                case QUERY_RESP:
                    postMainThread(() -> mView.quitTrans());
                    break;
                default:
                    break;
            }
        }
        super.importActionResult(actionResult);
    }

    @Override
    protected void onTransSuccess(RecvData recvData, EmvProcessResultEntity emvResult) {
        if (recvData == null) {
            postMainThread(() -> mView.showTransFailed());
            return;
        }
        String balance = recvData.getBalance();
        if (TextUtils.isEmpty(balance) || balance.length() < 12) {
            postMainThread(() -> mView.showTransFailed());
            return;
        }
        balance = balance.substring(balance.length() - 12, balance.length());
        mLog.debug("balance = {}", balance);
        if (!TextUtils.isDigitsOnly(balance)) {
            postMainThread(() -> mView.showError(App.sContext.getString(R.string.err_amount_format)));
            return;
        }
        mTransData.setAmount(balance);
        //存放金额符号，用于余额界面显示
        String symbol = recvData.getBalance().substring(13, 14);
        mLog.debug("符号 = {}", symbol);
        mTransData.setTemporary(symbol);
        //跳转到显示结果界面
        postMainThread(() -> mView.showQueryResp(mTransData));
    }

}
